<?php
    
    class DBConnection{

	private $_mysqli = NULL;
	
	public function Connect() {
      $this->_mysqli = new mysqli(DBSettings::DBHOST,
      							   DBSettings::DBUSER,
      							   DBSettings::DBPASSWORD,
      							   DBSettings::DATABASE);
          
          //Note charset should be set before any queries...
          $this->_mysqli->set_charset("utf8");
      
      // check connection
      if ($this->_mysqli->connect_errno) {
          Log::LogError("Connect failed: $this->_mysqli->connect_error");
          return false;
      }
      return true;
    }
	
	public function Close() {
        $this->_mysqli->close();
                $this->_mysqli = NULL;
    }
	
	public function GetSingleLineAsAssociativeArray(mysqli_stmt $stmt) {
		      
		$ret = array();          
	    $stmt->execute();
	   	
	    // bind results to named array
    	$meta = $stmt->result_metadata();
    	$fields = $meta->fetch_fields();
		
    	foreach($fields as $field) {
	      	$result[$field->name] = "";
	        $resultArray[$field->name] = &$result[$field->name];
   		}
		
		call_user_func_array(array($stmt, 'bind_result'), $resultArray);
		
		while($stmt->fetch()) {
	        foreach ($resultArray as $key => $value) {
	            $ret[$key] = $value;
	        }
	    }
		
		$stmt->close();
	    
	    return $ret;
	}
	
	public function Prepare($sql) {
	    if ($this->_mysqli == NULL) {
	            Log::LogError("Unable to connect to the database");
				return false;
	    }
	    
	    $stmt = $this->_mysqli->prepare($sql);
	    if ($stmt === false) {
	            Log::LogMessage("prepare of '$sql' failed " . $this->_mysqli->error);
	            return false;
	    }
	    
	    return $stmt;
    }
	
	public function RunAndFetchObjects(mysqli_stmt $stmt, $className, $nameOfPrimaryKey) {
		
        $ret = array();
        $stmt->execute();
               
        // bind results to named array
    	$meta = $stmt->result_metadata();
    	$fields = $meta->fetch_fields();
		
    	foreach($fields as $field) {
	      	$result[$field->name] = "";
	        $resultArray[$field->name] = &$result[$field->name];
   		}
		
		call_user_func_array(array($stmt, 'bind_result'), $resultArray);
 
        //hämta ut objekt av klassen '$className' ur resultatsettet
        while($stmt->fetch()) {
	        $resultObject = new $className();
	
	        foreach ($resultArray as $key => $value) {
	            $resultObject->$key = $value;
	        }
	        $ret[$resultObject->$nameOfPrimaryKey] = $resultObject;
	    }
        
   		$stmt->close();
        
        return $ret;
    }
	

} 